package com.mew.user.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mew.common.dc.db.LevelConfigService;
import com.mew.common.dc.db.ProfileService;
import com.mew.common.dc.mapper.OnlineGiftMapper;
import com.mew.common.enm.GoldProcessType;
import com.mew.common.entity.config.LevelVip;
import com.mew.common.entity.events.OnlineGift;
import com.mew.common.entity.user.Profile;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.events.OnlineGiftMessage;
import com.mew.common.rest.user.UserMoneyResponseMessage;
import com.mew.common.util.DateUtils;
import com.mew.user.config.EventsLastingConfig;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ztq
 * @since 2021-03-31
 */
@Service
public class OnlineGiftService extends ServiceImpl<OnlineGiftMapper, OnlineGift> {

    @Autowired
    private ProfileService profileService;

    @Autowired
    private LevelConfigService levelConfigService;

    @Autowired
    private EventsLastingConfig eventsLastingConfig;

    /**
     * 查询 没有就创建  时间不对也创建
     * @param uid
     * @return
     */
    public OnlineGift getOnlineGift(long uid){
        long[] golds = Arrays.stream(eventsLastingConfig.golds.split(",")).mapToLong(Long::parseLong).toArray();

        OnlineGift onlineGift = getById(uid);
        if (null==onlineGift){
            onlineGift = OnlineGift.builder().userId(uid).build();
        }

        if (null==onlineGift.getOnlineTime()|| !DateUtils.format(onlineGift.getOnlineTime(),"dd").equals(DateUtils.format(new Date(),"dd"))){
            //刷新或创建新的
            onlineGift.setOnlineTime(new Date());
            onlineGift.setOnlineSecond(0l);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < golds.length-1; i++) {
                builder.append("0");
            }
            onlineGift.setReceiveType(builder.toString());

            saveOrUpdate(onlineGift);
        }


        return onlineGift;
    }

    /**
     * 每日首次登录刷新
     * @param uid
     * @return
     */
    public OnlineGiftMessage refreshOnlineGift(long uid){

        long[] golds = Arrays.stream(eventsLastingConfig.golds.split(",")).mapToLong(Long::parseLong).toArray();


        OnlineGift onlineGift = getOnlineGift(uid);
        OnlineGiftMessage message = new OnlineGiftMessage();
        long onlineTime = new Date().getTime() - onlineGift.getOnlineTime().getTime() + onlineGift.getOnlineSecond();
        message.setOnlineTime(onlineTime/1000);

        String receiveType = getReceiveType(onlineGift.getReceiveType(), onlineTime);
        message.setReceiveType(receiveType);

        message.setBoxGold(Arrays.stream(golds).skip(1).toArray());
        LevelVip levelVip = levelConfigService.getLevelVipByUid(uid);
        message.setOnlineCoeff(levelVip.getOnlineCoeff());
        return message;
    }

    @NotNull
    private String getReceiveType(String receiveType, long onlineTime) {

        int[] onlinetimes = Arrays.stream(eventsLastingConfig.onlinetimes.split(",")).mapToInt(Integer::parseInt).toArray();

        //能开几个宝箱
        int num = 0;
        for (int i = 0; i < onlinetimes.length; i++) {
            num = i;
            if (onlineTime < onlinetimes[i]){
                break;
            }
        }

        //0未领取  1可领取 2已领取
        char[] chars = receiveType.toCharArray();
        for (int i = 0; i < num; i++) {
            if (chars[i]=='0'){
                chars[i]='1';
            }
        }
        return new String(chars);
    }

    /**
     * 领取奖励
     * @param type
     */
    public UserMoneyResponseMessage getGift(int type, long uid){

        int[] onlinetimes = Arrays.stream(eventsLastingConfig.onlinetimes.split(",")).mapToInt(Integer::parseInt).toArray();
        long[] golds = Arrays.stream(eventsLastingConfig.golds.split(",")).mapToLong(Long::parseLong).toArray();

        if (type<1){
            return new UserMoneyResponseMessage().buildByResponseCode(ResponseCode.ParamInvalid);
        }

        OnlineGift onlineGift = getOnlineGift(uid);
        long time = new Date().getTime()-onlineGift.getOnlineTime().getTime()+onlineGift.getOnlineSecond();

        //领哪个级别的
        int level = 0;
        for (int i = 0; i < onlinetimes.length; i++) {
            if (time<onlinetimes[i]){
                break;
            }
            level++;
        }

        if (type>level){
            //未到时间
            return new UserMoneyResponseMessage().buildByResponseCode(ResponseCode.DaysNotGet);
        }
        String receiveType = onlineGift.getReceiveType();

        if ("2".equals(receiveType.substring(type-1,type))){
            //领过
            return new UserMoneyResponseMessage().buildByResponseCode(ResponseCode.DaysGet);
        }

        LambdaQueryWrapper<OnlineGift> wrapper = new LambdaQueryWrapper<OnlineGift>()
                .eq(OnlineGift::getUserId, uid)
                .eq(OnlineGift::getReceiveType, receiveType);
        String newReceiveType = receiveType.substring(0, type - 1) + "2" + receiveType.substring(type);
        onlineGift.setReceiveType(newReceiveType);
        boolean update = update(onlineGift, wrapper);
        if (!update){
            return new UserMoneyResponseMessage().buildByResponseCode(ResponseCode.DaysGet);
        }

        long onlinegiftgold = golds[type];

        //记录
        //vip
        //加钱
        Profile profile = profileService.getRedisProfileById(uid);

        LevelVip vip = levelConfigService.getLevelVipConfig(profile.getVipLevel());
        onlinegiftgold *= (vip.getOnlineCoeff()+1000)/1000.0;
        profileService.doGold(profile,onlinegiftgold, GoldProcessType.Days);

        UserMoneyResponseMessage message = UserMoneyResponseMessage.builder().goldNumber(profile.getGoldNumber()).jewelNumber(profile.getJewelNumber()).build();

        return message;
    }


    public void enter(long uid){
        OnlineGift onlineGift = getOnlineGift(uid);
        OnlineGift newonlineGift = new OnlineGift();
        newonlineGift.setUserId(uid);
        newonlineGift.setOnlineTime(new Date());
        updateById(onlineGift);
    }

    public void exit(long uid,long date){
        OnlineGift onlineGift = getOnlineGift(uid);
        OnlineGift newonlineGift = new OnlineGift();
        newonlineGift.setUserId(uid);
        newonlineGift.setOnlineSecond(onlineGift.getOnlineSecond()+(System.currentTimeMillis()-date));
        updateById(onlineGift);
    }

}
